package com.eduspace.eduplatform.wares.listener;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author tbc tianbencai@e-eduspace.com
 * @version 1.0 {2016年5月4日 上午9:07:43}
 */
@Slf4j
@WebListener
public class ThreadPoolListener implements ServletContextListener {
    public static String LOCAL_THREAD_POOL = "localThreadPool";
    private final int threadPoolSize;

    {
        threadPoolSize = 4;
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("初始化异步连接池");
        ExecutorService threadPool = Executors.newFixedThreadPool(threadPoolSize);
        sce.getServletContext().setAttribute(LOCAL_THREAD_POOL, threadPool);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ExecutorService threadPool = (ExecutorService) sce.getServletContext().getAttribute("threadPool");
        log.info("关闭线程池: {}", threadPool);
        threadPool.shutdown();
    }

}
